package org.javaboy.vhr.service;

import org.javaboy.vhr.responseBean.ServerResponse;
import org.javaboy.vhr.mapper.DepartmentMapper;
import org.javaboy.vhr.model.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EmployeeService employeeService;

    public List<Department> getAllDepartment() {
        List<Department> list = departmentMapper.getDepartmentByParentId(-1);
        return list;
    }

    @Transactional
    public void addDept(Department department) {
        // 新增数据
        departmentMapper.insertSelective(department);
        // 查询父级的depPath
        String parentDeptPath = departmentMapper.getDepPathByParentId(department.getParentId());
        // 修改新增数据的depPath
        departmentMapper.updateDepPathById(department.getId(),parentDeptPath+"."+department.getId());
        // 修改父级的isParent字段为true
        departmentMapper.updateIsParentById(department.getParentId());
    }

    @Transactional
    public ServerResponse deleteDepartmentById(Integer id) {
        // 部门下有员工 不可删除
        int employeeCount = employeeService.getEmployeeByDeptId(id);
        if(employeeCount>0){
            return ServerResponse.error(1001,"部门下有员工不可删除");
        }
        // 部门下有子部门 不可删除
        int childrenCount = departmentMapper.getChildrenByParentId(id);
        if(childrenCount>0){
            return ServerResponse.error(1002,"部门下有子部门不可删除");
        }
        int result = departmentMapper.deleteByPrimaryKey(id);
        if(result!=1){
            return ServerResponse.error(1003,"删除失败");
        }
        return ServerResponse.success("删除成功");
    }
}
